package JUC;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 豆包LU
 * @date 2023/5/8 23:00
 */
public class ProducerConsumerDemo {
    private static final int QUEUE_CAPACITY = 2; // 队列容量
    private static final int PRODUCE_INTERVAL = 1000; // 生产者生产间隔
    private static final int CONSUME_INTERVAL = 500; // 消费者消费间隔
    private static final int PRODUCE_NUM = 5; // 生产者生产数量

    public static void main(String[] args) {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(QUEUE_CAPACITY); // 创建阻塞队列

        ExecutorService executor = Executors.newFixedThreadPool(3); // 创建线程池

        executor.execute(new Producer(queue)); // 启动生产者线程

        executor.execute(new Consumer(queue)); // 启动第一个消费者线程

        executor.execute(new Consumer(queue)); // 启动第二个消费者线程

        executor.shutdown(); // 关闭线程池
    }

    // 生产者线程
    private static class Producer implements Runnable {
        private final ArrayBlockingQueue<Integer> queue;

        public Producer(ArrayBlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            Random random = new Random();
            for (int i = 0; i < PRODUCE_NUM; i++) {
                try {
                    int n = random.nextInt(100);
                    System.out.println("生产者生产：" + n);
                    queue.put(n); // 将生产的元素放入队列
                    Thread.sleep(PRODUCE_INTERVAL); // 等待一段时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("生产者退出");
            System.exit(0); // 生产者退出程序
        }
    }

    // 消费者线程
    private static class Consumer implements Runnable {
        private final ArrayBlockingQueue<Integer> queue;

        public Consumer(ArrayBlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    int n = queue.take(); // 从队列中取出元素
                    System.out.println(Thread.currentThread().getName() + " 消费者消费：" + n);
                    Thread.sleep(CONSUME_INTERVAL); // 等待一段时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

